<?php

namespace app\admin\controller\wechat;

use app\common\controller\Backend;
use app\common\library\wechat\Wechat;
use EasyWeChat\Factory;
use think\Cache;
use think\Env;
use think\exception\DbException;
use think\response\Json;

/**
 * 微信粉丝管理
 *
 * @icon fa fa-circle-o
 */
class Fans extends Backend
{

    /**
     * Fans模型对象
     * @var \app\admin\model\wechat\Fans
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wechat\Fans;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['third','third.user'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 同步粉丝信息
     */
    public function sync()
    {
        $page_index = input('page', 0);
        $page_size = input('limit', 100);

        $app = Factory::officialAccount(Wechat::getConfig());
        $prefix = Env::get('prefix.prefix', 'meet');
        if ($page_index == 0) {
            $openid_list = [];
            $next_openid = null;

            $is_continue = true;

            do {
                $result = $app->user->list($next_openid);
                if (isset($result['errcode']) && $result['errcode'] != 0) {
                    $this->error($result["errmsg"]);
                }

                $next_openid = $result["next_openid"];

                if (!empty($result['data']['openid'])) {
                    $is_continue = true;
                    foreach ($result['data']['openid'] as $k => $v) {
                        $openid_list[] = $v;
                    }
                } else {
                    $is_continue = false;
                }

            } while ($is_continue);

            //将粉丝列表存入session
            Cache::set($prefix . '_wechat_fans_list', $openid_list, 3600);

            $total = count($openid_list);
            if ($openid_list % $page_size == 0) {
                $page_count = $total / $page_size;
            } else {
                $page_count = (int)($total / $page_size) + 1;
            }

            $data = array(
                'total' => $total,
                'page_count' => $page_count,
            );

            $this->success('', '', $data);
        } else {
            //微信粉丝列表
            $openid_list = Cache::get($prefix . '_wechat_fans_list');

            if (empty($openid_list)) {
                $this->error(__('Synchronization failed'));
            }

            $start = ($page_index - 1) * $page_size;
            $page_fans_openid_list = array_slice($openid_list, $start, $page_size);

            if (empty($page_fans_openid_list)) {
                $this->error(__('Synchronization failed'));
            }

            $result = $app->user->select($page_fans_openid_list);

            if (!empty($result['user_info_list'])) {
                foreach ($result['user_info_list'] as $k => $v) {
                    $data = [
                        'openid' => $v['openid'],
                        'unionid' => isset($v['unionid']) ? $v['unionid'] : '',
                        'is_subscribe' => $v['subscribe'],
                        'subscribe_time' => $v['subscribe_time'] ?? 0,
                        'subscribe_scene' => $v['subscribe_scene'] ?? '',
                        'unsubscribe_time' => $v['unsubscribe_time'] ?? 0
                    ];

                    $fans = $this->model->where('openid', '=', $v['openid'])->find();

                    if (empty($fans)) {
                        (new \app\admin\model\wechat\Fans())->save($data);
                    } else {
                        $fans->save($data);
                    }
                }
            }

            Cache::rm($prefix . '_wechat_fans_list');

            $this->success(__('Sync successful'));
        }
    }
}
